import type { HistoryItem } from '@/types/screenshot'
import { generateFilename } from './imageProcessor'

const HISTORY_KEY = 'screenshot_history'
const MAX_HISTORY_ITEMS = 20

/**
 * 保存服务类
 */
class SaveService {
  /**
   * 复制到剪贴板
   */
  async copyToClipboard(dataUrl: string): Promise<boolean> {
    try {
      // 检查是否在 Electron 环境中
      if (window.electronAPI) {
        const result = await window.electronAPI.copyToClipboard(dataUrl)
        return result.success
      }

      // Web 环境下使用 Clipboard API
      const blob = await this.dataUrlToBlob(dataUrl)
      await navigator.clipboard.write([
        new ClipboardItem({ 'image/png': blob })
      ])
      return true
    } catch (error) {
      console.error('复制到剪贴板失败:', error)
      return false
    }
  }

  /**
   * 保存到文件
   */
  async saveToFile(dataUrl: string, filename?: string): Promise<boolean> {
    try {
      const finalFilename = filename || generateFilename()

      // 检查是否在 Electron 环境中
      if (window.electronAPI) {
        const result = await window.electronAPI.saveScreenshot(dataUrl, finalFilename)
        if (result.success) {
          // 保存到历史记录
          await this.addToHistory(dataUrl, result.path)
        }
        return result.success
      }

      // Web 环境下直接下载
      const link = document.createElement('a')
      link.href = dataUrl
      link.download = finalFilename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      await this.addToHistory(dataUrl)
      return true
    } catch (error) {
      console.error('保存文件失败:', error)
      return false
    }
  }

  /**
   * 自动保存（不弹窗）
   */
  async autoSave(dataUrl: string): Promise<{ success: boolean; path?: string }> {
    try {
      const filename = generateFilename()

      // 检查是否在 Electron 环境中
      if (window.electronAPI) {
        const result = await window.electronAPI.autoSaveScreenshot(dataUrl, filename)
        if (result.success) {
          await this.addToHistory(dataUrl, result.path)
        }
        return result
      }

      // Web 环境下保存到 IndexedDB
      await this.addToHistory(dataUrl)
      return { success: true }
    } catch (error) {
      console.error('自动保存失败:', error)
      return { success: false }
    }
  }

  /**
   * 添加到历史记录
   */
  async addToHistory(dataUrl: string, filePath?: string): Promise<void> {
    try {
      const history = await this.getHistory()
      
      // 生成缩略图
      const thumbnail = await this.generateThumbnail(dataUrl, 150)

      const item: HistoryItem = {
        id: Date.now().toString(),
        timestamp: Date.now(),
        thumbnail,
        filePath,
      }

      history.unshift(item)

      // 限制历史记录数量
      if (history.length > MAX_HISTORY_ITEMS) {
        history.splice(MAX_HISTORY_ITEMS)
      }

      localStorage.setItem(HISTORY_KEY, JSON.stringify(history))
    } catch (error) {
      console.error('添加到历史记录失败:', error)
    }
  }

  /**
   * 获取历史记录
   */
  async getHistory(): Promise<HistoryItem[]> {
    try {
      const data = localStorage.getItem(HISTORY_KEY)
      return data ? JSON.parse(data) : []
    } catch (error) {
      console.error('获取历史记录失败:', error)
      return []
    }
  }

  /**
   * 删除历史记录项
   */
  async deleteHistoryItem(id: string): Promise<void> {
    try {
      const history = await this.getHistory()
      const filtered = history.filter(item => item.id !== id)
      localStorage.setItem(HISTORY_KEY, JSON.stringify(filtered))
    } catch (error) {
      console.error('删除历史记录失败:', error)
    }
  }

  /**
   * 清空历史记录
   */
  async clearHistory(): Promise<void> {
    try {
      localStorage.removeItem(HISTORY_KEY)
    } catch (error) {
      console.error('清空历史记录失败:', error)
    }
  }

  /**
   * DataURL 转 Blob
   */
  private async dataUrlToBlob(dataUrl: string): Promise<Blob> {
    const response = await fetch(dataUrl)
    return response.blob()
  }

  /**
   * 生成缩略图
   */
  private async generateThumbnail(dataUrl: string, maxWidth: number): Promise<string> {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = () => {
        const ratio = maxWidth / img.width
        const width = maxWidth
        const height = img.height * ratio

        const canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        const ctx = canvas.getContext('2d')

        if (!ctx) {
          reject(new Error('无法获取 Canvas 上下文'))
          return
        }

        ctx.drawImage(img, 0, 0, width, height)
        resolve(canvas.toDataURL('image/jpeg', 0.7))
      }
      img.onerror = reject
      img.src = dataUrl
    })
  }
}

// 导出单例
export const saveService = new SaveService()

